package com.springmvc.interceptor;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.springmvc.common.ErrorInfo;
import com.springmvc.exception.ControllerException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.Ordered;
import org.springframework.stereotype.Component;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.ServletRequestBindingException;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * 统一处理controller异常
 */
@Component
@Slf4j
public class ControllerExceptionHandler implements HandlerExceptionResolver, Ordered
{

    private int order = Ordered.HIGHEST_PRECEDENCE;

    @Override
    public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
    {

        log.error("-------controller exception-------", ex);

        Map<String, Object> map = new HashMap<String, Object>();

        if (ex instanceof ControllerException)
        {
            ControllerException runtimeException = (ControllerException) ex;
            map.put("code", runtimeException.getCode());
            map.put("msg", runtimeException.getMessage());
        } else if (ex instanceof HttpRequestMethodNotSupportedException)
        {
            map.put("code", ErrorInfo.REQUEST_METHOD_ERROR.getErrCode());
            map.put("msg", ErrorInfo.REQUEST_METHOD_ERROR.getErrName());
        } else if (ex instanceof ServletRequestBindingException)
        {
            map.put("code", ErrorInfo.REQUEST_PARAMETER_IS_INCORRECT.getErrCode());
            map.put("msg", ErrorInfo.REQUEST_PARAMETER_IS_INCORRECT.getErrName());
        } else
        {
            map.put("code", ErrorInfo.ERROR_CODE_ERROR.getErrCode());
            map.put("msg", ErrorInfo.ERROR_CODE_ERROR.getErrName());
        }

        try
        {
            response.setHeader("Content-Type", "application/json;charset=utf-8");
            response.setHeader("Cache-Control", "no-cache");
            response.getWriter().print(JSON.toJSONString(map, SerializerFeature.WriteDateUseDateFormat));
        } catch (IOException e)
        {
            log.error("异常信息：{}", e);
        }
        return new ModelAndView();
    }

    @Override
    public int getOrder()
    {
        return order;
    }
}
